import base64, json
from .abstract import ContentRecognizer
# 文字识别接口地址
URL_ZXRJY = 'http://work.zxrjy.net:8877/predict/ocr_system'
URL_ENABC = 'http://enabc.net:8877/predict/ocr_system'
#OCR识别器类
class PaddleOcrRecognizer(ContentRecognizer):
    def __init__(self, url):
        self.url = url
    #识别接口
    def onRecog(self, imgData):
        #imgData: 带有文件头部信息的二进制位图数据
        data = {
          'images': [base64.b64encode(imgData).decode()]
        }
        headers = {'Content-Type': 'application/json'}
        res = self.post(self.url, json.dumps(data).encode(), headers)
        if int(res['status']) != 0:
            raise Exception(res['msg'])
        results = res['results']
        if not results:
            raise Exception('No results.')
        res = results[0]
        lines=[]
        words = []
        lastY = 0
        for item in res:
            lt, rt, rb, lb = item['text_region']
            text = item['text']
            word = {'x': lt[0], 'y': lt[1], 'width': rt[0] -lt[0], 'height': lb[1] -lt[1], 'text': text}
            if lastY < lt[1]:
                lastY = lt[1]
                words = [word]
                lines.append(words)
                continue
            words.append(word)
        return lines
    def onCancel(self):pass
# 本地 Paddle 识别器类
class LocalPaddleOcrRecognizer(ContentRecognizer):
    # 识别文本框
    def detect(self, imgData):
        headers = {'Content-Type': 'image/*'}
        url = 'http://localhost:19888/detect'
        return self.post(url, imgData, headers)
    # 识别文本框中的文字
    def recog(self, imgData, boxes):
        headers = {'Content-Type': 'image/*'}
        url = 'http://localhost:19888/recog/' + self.getBoxesString(boxes)
        return self.post(url, imgData, headers)
    # 获取一个box的字符串
    def getBoxString(self, box):
        return ','.join(box) + ';'
    # 获取一组box的字符串
    def getBoxesString(self, boxes):
        return "".join([self.getBoxString(i) for i in boxes])
    # 识别接口
    def onRecog(self, imgData):
        # imgData: 带有文件头部信息的二进制位图数据
        boxes = self.detect(imgData)
        res = self.recog(imgData, boxes)
        res = '\n'.join(res)
        return [
            [{'x':0, 'y':0, 'width':0, 'height':0, 'text':res}]
        ]
    def onCancel(self):pass
